﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using DbfViewer.Models.DataTypes;
using DbfViewer.Commands;
using DbfViewer.Models;
using System.Windows.Input;

namespace DbfViewer.ViewModels
{
	public class AddFieldViewModel : ViewModelBase
	{
		public AddFieldViewModel()
		{
			InitializeDataTypes();
		}

		private void InitializeDataTypes()
		{
			datatypes.Add(new Character());
			datatypes.Add(new Numeric());
			datatypes.Add(new Float());
			datatypes.Add(new Logical());
			datatypes.Add(new Date());
		}

		private string name;
		public string Name
		{
			get
			{
				return name;
			}
			set
			{
				name = value;
				OnPropertyChanged("Name");
			}
		}

		private ObservableCollection<IDataType> datatypes = new ObservableCollection<IDataType>();
		public ObservableCollection<IDataType> DataTypes
		{
			get
			{
				return datatypes;
			}
			set
			{
				datatypes = value;
				OnPropertyChanged("DataTypes");
			}
		}

		private IDataType selectedValue = null;
		public IDataType SelectedValue
		{
			get { return selectedValue; }
			set
			{
				selectedValue = value;
				OnPropertyChanged("SelectedValue");
			}
		}

		private bool? dialogResult = null;
		public bool? DialogResult
		{
			get { return dialogResult; }
			set
			{
				dialogResult = value;
				OnPropertyChanged("DialogResult");
			}
		}

		private DelegateCommand okCommand;
		public ICommand OkCommand
		{
			get { return okCommand ?? (okCommand = new DelegateCommand(Ok, CanExecute)); }
		}
		private void Ok()
		{
			DialogResult = true;
		}
		private bool CanExecute()
		{
			return IsNameValid() && SelectedValue != null;
		}

		private DelegateCommand cancelCommand;
		public ICommand CancelCommand
		{
			get { return cancelCommand ?? (cancelCommand = new DelegateCommand(Cancel)); }
		}
		private void Cancel()
		{
			DialogResult = false;
		}

		private bool IsNameValid()
		{
			if (name == null)
			{
				return false;
			}
			return new FieldNameRule().Validate(Name, System.Globalization.CultureInfo.CurrentCulture).IsValid;
		}
	}
}
